package model

import (
	"gorm.io/gorm"
	"time"
)

type (
	LendModel interface {
		IsLend(bookId uint64)  (bool, error)
	}

	defaultLendModel struct {
		conn *gorm.DB
		table string
	}

	Lend struct {
		gorm.Model
		UserId  uint `json:"userId" gorm:"comment:用户id;not null"` //用户id
		BookId  uint `json:"bookId"  gorm:"comment:图书id;not null"`      //图书id
		LendTime time.Time `json:"lendTime" gorm:"comment:借阅时间;not null"` //借阅时间
	}
)

func NewLendModel(conn *gorm.DB) LendModel {
	//如果没有表则自动构建表
	conn.AutoMigrate(Lend{})

	return &defaultLendModel{
		conn : conn,
		table:   "lends",
	}
}


func (d defaultLendModel) IsLend(bookId uint64) (bool, error) {
	var lend []Lend
	err := d.conn.Where("book_id=?", bookId).Find(&lend).Error
	if err != nil {
		return false, err
	}
	if len(lend) > 0 {
		return true, err
	}
	return false, nil
}
